import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import 'package:get/get.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:flutter_getx/app/service/user_info_service.dart';
import 'package:intl/intl.dart';

import '../../../../data/api/api.dart';
import '../../../../service/local_storage_service.dart';

class EditMeController extends GetxController {
  UserInfoService userInfoService = Get.find();
  LocalStorageService localStorageService = Get.find();
  Api api = new Api();

  final TextEditingController nickNameTec = new TextEditingController();
  final TextEditingController introTec = new TextEditingController();
  DateTime dateTime = DateTime.now();
  RxString birthday = "".obs;
  RxBool gender = true.obs;

  void showDateTimePicker() {
    DatePicker.showDatePicker(Get.context!,
        showTitleActions: true,
        minTime: DateTime(1949, 10, 1),
        maxTime: DateTime(2022,12, 1), onConfirm: (date) {
      this.dateTime = date;
      this.birthday.value = DateFormat("yyyy-MM-dd").format(this.dateTime);
    }, currentTime: this.dateTime, locale: LocaleType.zh);
  }

  Future<void> updateInfo() async {
    var r = await api.updateUserInfo(userInfoService.userInfo.value.id!, gender.value, nickNameTec.text, birthday.value, introTec.text);
    if (r) {
      userInfoService.userInfo.value.gender = gender.value;
      userInfoService.userInfo.value.nickname = nickNameTec.text;
      userInfoService.userInfo.value.birthday = birthday.value;
      userInfoService.userInfo.value.intro = introTec.text;
      // 需要刷新
      userInfoService.userInfo.refresh();
      // 本地存储个人信息
      localStorageService.setData(localStorageService.userInfoKey, userInfoService.userInfo.value.toJson());

      EasyLoading.showSuccess("更新成功");
    }
  }

  @override
  void onInit() {
    if (userInfoService.userInfo.value.gender == null) {
      gender.value = true;
    } else {
      gender.value = userInfoService.userInfo.value.gender!;
    }
    this.nickNameTec.text = userInfoService.userInfo.value.nickname!;
    if (userInfoService.userInfo.value.intro != null ) {
      this.introTec.text = userInfoService.userInfo.value.intro!;
    }
    if (userInfoService.userInfo.value.birthday !=null && userInfoService.userInfo.value.birthday != "") {
      this.dateTime = DateTime.parse(userInfoService.userInfo.value.birthday!);
    }
    this.birthday.value = DateFormat("yyyy-MM-dd").format(this.dateTime);


    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {}
}
